import json
import sys
from lib.apis import aep_device_command


def issue_command(appKey='pUxUqtQiPf2', appSecret='OFf8fLb3Ou', masterKey='491bad06fffe4269a2152210e6a5bd27', productId=17048069, deviceId='17048069123456'):
    body = {
        'productId': productId,
        'deviceId': deviceId,
        'deviceGroupId': None,
        'content': {
            'serviceIdentifier': 'user_cmd_data',
            'params': {
                'user_data_string': '123'
            }
        },
        'operator': 'cjl',
        'level': 1,
        'ttl': 7200,
    }
    body_json = json.dumps(body)
    result = aep_device_command.CreateCommand(appKey, appSecret, masterKey, body_json)
    return result

def query_command(appKey='pUxUqtQiPf2', appSecret='OFf8fLb3Ou', masterKey='491bad06fffe4269a2152210e6a5bd27', commandId='1234567890',productId=17048069, deviceId='17048069123456'):
    result = aep_device_command.QueryCommand(appKey, appSecret, masterKey, commandId, productId, deviceId)
    return result
    

if __name__ == '__main__':
    result = issue_command()
    # 将 bytes 对象解码为字符串
    result_str = result.decode('utf-8')
    # 将字符串转换为字典
    result_dict = json.loads(result_str)
    if result_dict.get('code') == 0:
        print('issue command success,result:'+ str(result_dict))
        commandId = result_dict.get('result').get('commandId')
        result = query_command(commandId=commandId)
        
        result_str = result.decode('utf-8')
        
        result_dict = json.loads(result_str)
        if result_dict.get('code') == 0 and result_dict.get('result').get('resultCode') == 'DELIVERED':
            print('command delivered,result:'+ str(result_dict))
        else:
            print('query command status, result:' + str(result_dict))
    else:
        print('issue command failed')
